package com.hongxun.design.activitys;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.bean.Exploration;
import com.hongxun.design.bean.ReconnaissanceBean;
import com.hongxun.design.bean.SpanBean;
import com.hongxun.design.bean.gpsbean.RootCode;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.interfaces.UpdateMap;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.listeners.MyLocationListenner;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.MBaiduMap;
import com.hongxun.design.ui.dialogstyle.LoadUtil;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.PopwindowUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.GetFileUtil;
import com.hongxun.design.utils.fileutil.SetFileUtil;
import com.hongxun.design.utils.gpsutil.GPS_TOOL;
import com.hongxun.design.utils.gpsutil.GaussXYDeal;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.imageutil.UriUtil;
import com.hongxun.design.utils.maputil.Gps2BaiDu;
import com.hongxun.design.utils.mohe.MoHeSDKInIt;
import com.pop.android.common.beans.WzOutLocation;
import com.pop.android.common.util.EvilTransform;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.lang.Integer.parseInt;

/**
 * Created by zerdoor_pc on 2016/5/5.
 * 定位界面
 */
public class ReconnaissanceActivity extends BaseActivity implements HeadSecond, UpdateMap {

    public static LatLng currentPt;
    MapView mMapView;
    BaiduMap mBaiduMap;
    TextView reconnaissance_intensity_icon, reconnaissance_intensity,
            reconnaissance_intensity_word, reconnaissance_accuracy,
            headsecond_button_icon, altitude, longitude, latitude, quality_flag;
    int changeRTK;//RTK类型
    boolean disPlay;//下方条目显示
    ReconnaissanceBean bean;
    LinearLayout headsecond_button_item;
    private int[] images = new int[]{R.mipmap.signal0, R.mipmap.signal1, R.mipmap.signal2,
            R.mipmap.signal3, R.mipmap.signal4, R.mipmap.signal5};
    public MyLocationListenner myListener;
    SimpleDraweeView drag_mark, reconnaissance_image;
    public static HeadSecondControlPanel headsecond_layout;

    private static Handler DGPSHandler;//DGPS接收处理
    int GPSCODE = 1000;//GPS设置回调
    private static LoadUtil loadutil;//dialog状态更新
    private static final int update = 2;
    private static final int ERRORBACK = 3;
    private static final int SUCCEED = 4;
    static Location mlocation;//GPS返回数据

    public static String projectType = "11";//初始新建与拆旧状态
    private Handler pointHandler;//新建与拆旧点位接收
    List<Exploration> pointData;//新建与拆旧点位集合
    MBaiduMap baidumapstyle;//百度地图
    BDLocation location;//百度定位数据
    boolean isonResumeupdate = false;//第一次进入界面标记
    static boolean isGps = true;//判断是否为gps获取经纬
    static boolean isBox = false;//判断是否为魔盒获取经纬
    static boolean getGps = false;//判断是否获取gps经纬

    private RadioGroup radioGroup;//定位模式
    private RadioButton radioButton3;//拖动定位

    @Override
    protected void onDestroy() {
        MyApp.isDistance = false;//退出时清空数据
        headsecond_layout = null;
        if (loadutil != null) loadutil.outClear();
        loadutil = null;
        if (baidumapstyle != null) baidumapstyle.onDestroy();
        if (handler != null) handler = null;
        if (mohe != null) mohe.close();
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reconnaissance);
        isGps = true;
        MyApp.currExploration.clear();
        findBar();
        findView();
        initialization();
    }

    private ReconnaissanceBean getData() {
        bean = DataUtil.getReconnaissanceBean();
        return bean;
    }

    @Override
    public void findBar() {
        headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.headsecond_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean(IconSourse.ADD + "", View.VISIBLE, R.color.bar_right, ListenerSet.back, MyApp.currProject.getProject_name(), R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        headsecond_layout.setSearchTitle(MyApp.currProject.getProject_name());
        headsecond_layout.setSearchOnclick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putString(MString.TYPE, MString.projectChoice);
                IntentToActivity.intent(mActivity, CreateProjectAttributeCodeActivity.class, bundle);
            }
        });
        headsecond_layout.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopwindowUtil.openPop((TextView) view, mActivity, DataUtil.getPopItem());
            }
        });
    }


    @Override
    protected void findView() {
        findViewAndInit_MapButton();
        /***左上方信号**/
        reconnaissance_intensity_icon = (TextView) findViewById(R.id.reconnaissance_intensity_icon);
        reconnaissance_intensity = (TextView) findViewById(R.id.reconnaissance_intensity);
        reconnaissance_intensity_word = (TextView) findViewById(R.id.reconnaissance_intensity_word);
        reconnaissance_accuracy = (TextView) findViewById(R.id.reconnaissance_accuracy);
        reconnaissance_image = (SimpleDraweeView) findViewById(R.id.reconnaissance_image);
        /***mark**/
        drag_mark = (SimpleDraweeView) findViewById(R.id.drag_mark);
        /***下方栏目显示按钮**/
        headsecond_button_icon = (TextView) findViewById(R.id.headsecond_button_icon);
        headsecond_button_item = (LinearLayout) findViewById(R.id.headsecond_button_item);
        altitude = (TextView) findViewById(R.id.headsecond_altitude);
        longitude = (TextView) findViewById(R.id.headsecond_longitude);
        latitude = (TextView) findViewById(R.id.headsecond_latitude);
        quality_flag = (TextView) findViewById(R.id.quality_flag);
        quality_flag.setVisibility(View.GONE);

        //定位模式切换
        radioGroup = (RadioGroup) findViewById(R.id.rgroup);
        radioButton3 = (RadioButton) findViewById(R.id.rbtn3);


        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (MyApp.currProject.getProject_id().length() == 0 && MyApp.currProject.getUUID().length() == 0) {
                    ToastShow.showShort(mActivity, "请选择一个项目！");
                    return;
                }
                switch (checkedId) {
                    case R.id.rbtn1://手机
                        isBox = false;
                        isGps = true;
                        changeRTK = R.mipmap.signal_phone;
                        quality_flag.setVisibility(View.VISIBLE);
                        drag_mark.setVisibility(View.VISIBLE);
                        changeToPhoneAccurate();
                        break;
                    case R.id.rbtn2://外设
                        isBox = true;
                        isGps = false;
                        changeRTK = R.mipmap.signal_rtk;
                        if (mohe != null) mohe.close();
                        quality_flag.setVisibility(View.GONE);
                        drag_mark.setVisibility(View.GONE);
                        changeToBoxAccurate();
                        break;
                    case R.id.rbtn3://拖动
                        isBox = false;
                        isGps = false;
                        GPS_TOOL.isOn = false;
                        closeGps();
                        drag_mark.setVisibility(View.VISIBLE);
                        if (currMark == null) {
                            addPoint();
                        } else {
                            currMark.remove();
                            currMark = null;
                            if (currentPt != null)
                                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));
                        }
                        if (MyApp.gps_tool != null) MyApp.gps_tool.close();
                        if (mohe != null) mohe.close();
                        break;
                }
            }
        });
        super.findView();
    }


    /**
     * 设置地图的放大缩小按钮*
     */

    private void findViewAndInit_MapButton() {
        baidumapstyle = (MBaiduMap) findViewById(R.id.baidumapstyle);
        baidumapstyle.setPositionClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inItLocation_first();//定位当前位置
            }
        });
        mMapView = baidumapstyle.getMapView();
        mBaiduMap = baidumapstyle.getBaiduMap();
        baidumapstyle.setIsNewBlude();
        baidumapstyle.setNeedGps();
        SetOnMapStatusChangeListener();
    }

    @Override
    protected void initialization() {
        SetTypeface.set(reconnaissance_intensity_icon, IconSourse.SATELLITE);//设置信号图标
        SetTypeface.set(headsecond_button_icon, IconSourse.ADD);//设置按钮图标
        mBaiduMap = mMapView.getMap();
        changeRTK = R.mipmap.signal_phone;
        addPointHandler();//点位接收器
        addDGPSHandler();//DGPS处理器
        addHandler();
        getData();//获取初始数据源
        setPosition();
        ChangeGPSStyle();
        if (currentPt == null) {
            inItLocation_first();
        }
        //点位采集地图：新增其它点位展示
        getExplorationList();
        super.initialization();
    }

    public static void setNew() {
        if (handler != null) handler.sendEmptyMessage(1);
    }

    private static Handler handler;

    private void addHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                setPosition();
            }
        };
    }

    //设置拆旧换新
    private void setPosition() {
        boolean empty1 = TextUtils.isEmpty(MyApp.currProject.getLat());
        boolean empty2 = TextUtils.isEmpty(MyApp.currProject.getLng());
        if (!empty1 && !empty2) {
            currentPt = new LatLng(Double.parseDouble(MyApp.currProject.getLat()), Double.parseDouble(MyApp.currProject.getLng()));
            bean.setCurrentPt(currentPt);
            longitude.setText(bean.getCurrentPt().longitude + "");
            latitude.setText(bean.getCurrentPt().latitude + "");
        }
    }

    /**
     * 状态更新*
     */
    private void updeteData(ReconnaissanceBean bean) {
        if (bean.getType().equals(Constant.RTK)) {
            changeRTK = R.mipmap.signal_rtk;
        } else {
            changeRTK = R.mipmap.signal_phone;
        }
        if (bean.getCurrentPt() != null) {
            //更新
            reconnaissance_intensity.setText(bean.getStrengthValue());//设置信号强度
            reconnaissance_intensity_word.setText(getStrength(parseInt(bean.getStrengthValue())));
            reconnaissance_accuracy.setText(bean.getAccuracy());//设置信号精度
            altitude.setText(bean.getAltitude());
            longitude.setText(bean.getCurrentPt().longitude + "");
            latitude.setText(bean.getCurrentPt().latitude + "");
        } else {
            //坐标为空
            ToastShow.showLong(mActivity, "坐标为空!");
        }

        GPS_TOOL.isOn = false;
        MyApp.gps_tool.close();

    }


    /**
     * 卫星数转化为信号*
     */
    private String getStrength(int value) {
        String s = "";
        int i = 0;
        switch (value / 4) {
            case 0:
                s = "非常差";
                i = 0;
                break;
            case 1:
                s = "较差";
                i = 1;
                break;
            case 2:
                i = 2;
                s = "差";
                break;
            case 3:
                i = 3;
                s = "一般";
                break;
            case 4:
                i = 4;
                s = "好";
                break;
            case 5:
                i = 5;
                s = "很好";
                break;
            default:
                i = 5;
                s = "非常好";
                break;
        }
        reconnaissance_image.setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + images[i]));
        return s;
    }


    /**
     * 百度定位开启定位图层*
     */
    private void inItLocation() {
        mBaiduMap.setMyLocationEnabled(true);
        myListener = MyLocationListenner.getint(mMapView, this);
        myListener.setIsFirstLoc(false);
        myListener.setCountinue(true);
    }

    private void inItLocation_first() {
        mBaiduMap.setMyLocationEnabled(true);
        myListener = MyLocationListenner.getint(mMapView, this);
        myListener.setIsFirstLoc(true);
        myListener.setCountinue(false);
    }

    MoHeSDKInIt mohe;

    /**
     * 手机精确定位
     **/
    public void changeToPhoneAccurate() {
        //手机精确定位
        GPS_TOOL.isOn = true;
        isGps = true;
        GPS();
    }

    /**
     * 魔盒精确定位
     **/
    public void changeToBoxAccurate() {
        //魔盒精确定位
        isBox = true;
        if (mohe == null) mohe = MoHeSDKInIt.getInstence();
        mohe.open();//打开蓝牙
    }


    boolean isfirstdata = true;

    public void setLatlng(WzOutLocation wzOutLocation) {
        try {

            Location location = EvilTransform.transform(wzOutLocation);
            mlocation = location;//将坐标值传给本页对象
            MyLog.L("bluetooth:location" + wzOutLocation.getLatitude() + "---" + wzOutLocation.getLongitude());
            currentPt = new LatLng(wzOutLocation.getLatitude(), wzOutLocation.getLongitude());//获取到的原始GPS坐标
            if (currentPt != null) {
                //百度数据
                int StrengthValue = parseInt(wzOutLocation.getExtraMap().get(WzOutLocation.SATELLITES_IN_USE));
                String ACCURACY = wzOutLocation.getExtraMap().get(WzOutLocation.ACCURACY_RANGE);
                String quality = wzOutLocation.getExtraMap().get(WzOutLocation.QUALITY_FLAG);
                quality_flag.setText("定位获取中...     模式：" + quality);
                quality_flag.setVisibility(View.VISIBLE);
                if (StrengthValue <= 0) {
                    bean.setStrengthValue(0 + "");
                } else {
                    bean.setStrengthValue(StrengthValue + "");
                }


                if (location.getAltitude() == 4.9E-324) {
                    bean.setAltitude("");
                } else {
                    bean.setAltitude(location.getAltitude() + "");
                }

                bean.setAccuracy(ACCURACY + "");
                MyLog.L("bluetooth:location" + currentPt.latitude + "---" + currentPt.longitude);
                currentPt = Gps2BaiDu.to(currentPt);//获取差分数据
                MyLog.L("bluetooth:location" + currentPt.latitude + "---" + currentPt.longitude);
                if (currMark == null) {
                    addPoint();
                } else {
                    currMark.setPosition(currentPt);
                }
                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));//将位置设为中心点

                bean.setCurrentPt(currentPt);

                updeteData(bean);
                DGPSHandler.sendEmptyMessage(SUCCEED);
            }
            if (isfirstdata) {
                isfirstdata = false;
                loadutil.close();
            }
        } catch (Exception e) {
        }
    }

    public void openDialog() {
        isfirstdata = true;

        loadutil = LoadUtil.getIntence(this);
        loadutil.startDialog();
        loadutil.setText("正在获取数据！");
    }


    public void ChangeGPSStyle() {
        isGps = false;
        isBox = false;
        closeGps();
        if (currMark == null) {
            addPoint();
        } else {
            currMark = null;
        }
        MyApp.gps_tool.close();

    }


    private void openPhone() {
        bean.setType(Constant.PHONE);
        inItLocation();//重新定位
    }

    private void startDGPS() {

        if (MyApp.gps_tool == null) MyApp.gps_tool = GPS_TOOL.getIntence(this);//实例化定位类
        if (MyApp.gps_tool.openGPSSettings())//检查定位GPS是否打开?
        {
            //如打开开始定位
            openDGPS();//DGPS定位
        } else {
            //未打开跳转到设置
            this.startActivityForResult(MyApp.gps_tool.intent, GPSCODE);//跳转到gps设置界面
        }
    }

    private void openDGPS() {
        MyApp.gps_tool.getLocation();//开始gps定位
        loadutil = LoadUtil.getIntence(this);
        loadutil.startDialog();
        loadutil.setText("正在获取GPS数据！");
    }

    /**
     * gps返回刷新*
     */
    public static void setUpdateGps() {
        if (MyApp.location != null && DGPSHandler != null && getGps) {
            mlocation = MyApp.location;//将坐标值传给本页对象
            currentPt = new LatLng(mlocation.getLatitude(), mlocation.getLongitude());//获取到的原始GPS坐标
            DGPSHandler.sendEmptyMessage(update);//进行更新差分计算
        }
    }

    /**
     * gps超时刷新*
     */
    static boolean isERROR = false;

    public static void setCloseUpdateGps() {
        if (MyApp.location != null && DGPSHandler != null && getGps) {
            try {
                mlocation = MyApp.location;//将坐标值传给本页对象
                currentPt = Gps2BaiDu.to(new LatLng(mlocation.getLatitude(), mlocation.getLongitude()));//获取到的原始GPS坐标
                DGPSHandler.sendEmptyMessage(SUCCEED);//更新坐标
                isERROR = true;
            } catch (Exception e) {
            }


        }
    }

    /**
     * gps返回操作刷新*
     */
    public static void setUpdateGpsCode() {
        if (MyApp.location != null && DGPSHandler != null && getGps && loadutil != null) {
            DGPSHandler.sendEmptyMessage(5);
        }
    }

    /**
     * gps返回操作刷新*
     */
    public static void setUpdateGpsCode(String x) {
        if (MyApp.location != null && DGPSHandler != null && getGps && loadutil != null) {

            if (loadutil != null) loadutil.setText(x);
            DGPSHandler.sendEmptyMessage(5);
        }
    }

    /**
     * gps返回打开dialog*
     */
    public static void setGpsDialog() {
        DGPSHandler.sendEmptyMessage(6);
    }

    RootCode root;

    private void addDGPSHandler() {
        DGPSHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
//                    {"status":-2,"msg":"不存在距离小于50KM的基站数据","data":{"y":0,"x":0}}
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            root = FastJsonUtil.getAppli((String) msg.obj);
                            if (!root.msg.equalsIgnoreCase("success")) {
                                ToastShow.showShort(mActivity, "获取基站差分值失败！");
                                error();
                            } else if (root.data != null) {
                                if (loadutil != null) loadutil.setText("获取基站差分值成功！");
                                if (loadutil != null) loadutil.setText("正在计算差分经纬...");
                                ToastShow.showShort(mActivity, "正在计算差分经纬...");
                                LatLng itude = GaussXYDeal.GaussToBLToGauss(currentPt.longitude, currentPt.latitude);
                                double mlatitude = itude.latitude - root.data.carin_x;
                                double mlongitude = itude.longitude - root.data.carin_y;
                                currentPt = Gps2BaiDu.to(GaussXYDeal.GaussToBL(mlatitude, mlongitude));//获取差分数据

                                DGPSHandler.sendEmptyMessage(SUCCEED);
                            }
                        } else {
                            ToastShow.showShort(mActivity, "请求差分数据异常，将直接使用GPS数据!");
                            error();
                            DGPSHandler.sendEmptyMessage(SUCCEED);
                        }
                        break;
                    case update:
                        if (MyApp.NetWorkConnect) {
                            if (loadutil != null) loadutil.setText("正在获取差分数据！");
                            getDifferenceData();
                        } else {
                            error();
                        }
                        break;
                    case ERRORBACK:
                        //基站获取失败等其他异常
                        openPhone();
                        break;

                    case 7:
                        if (loadutil != null) loadutil.setText("关闭");
                        isERROR = false;
                        try {
                            if (loadutil != null) loadutil.close();
                        } catch (Exception e) {
                        }
                        ChangeGPSStyle();

                        break;
                    case SUCCEED:
                        //成功后数据加载
                        if (loadutil != null) loadutil.setText("重新更新地图...");
                        if (isGps && mlocation != null) {
                            bean.setAltitude(mlocation.getAltitude() + "");
                            bean.setStrengthValue(MyApp.gps_tool.getCount() + "");//设置信号强度
                            bean.setAccuracy(mlocation.getAccuracy() + "");
                        } else if (location != null) {
                            //百度数据
                            if (location.getSatelliteNumber() <= 0) {
                                bean.setStrengthValue(0 + "");
                            } else {
                                bean.setStrengthValue(location.getSatelliteNumber() + "");
                            }
                            if (location.getAltitude() == 4.9E-324) {
                                bean.setAltitude("");
                            } else {
                                bean.setAltitude(location.getAltitude() + "");
                            }

                            bean.setAccuracy(location.getRadius() + "");
                        }
                        bean.setCurrentPt(currentPt);
                        if (currMark == null) {
                            addPoint();
                        } else {
                            currMark.setPosition(currentPt);
                        }
                        updeteData(bean);

                        if (isERROR) {
                            DGPSHandler.sendEmptyMessage(7);
                        } else {
                            try {
                                if (loadutil != null) loadutil.close();
                            } catch (Exception e) {
                            }
                        }

                        break;
                    case 5:
                        //更新信号
                        mlocation = MyApp.location;//将坐标值传给本页对象
                        bean.setAltitude(mlocation.getAltitude() + "");
                        bean.setStrengthValue(MyApp.gps_tool.getCount() + "");//设置信号强度
                        bean.setAccuracy(mlocation.getAccuracy() + "");
                        reconnaissance_intensity.setText(bean.getStrengthValue());//设置信号强度
                        reconnaissance_intensity_word.setText(getStrength(parseInt(bean.getStrengthValue())));
                        reconnaissance_accuracy.setText(bean.getAccuracy());//设置信号精度
                        break;
                    case 6:
                        startDGPS();
                        break;
                    case HttpStringUtil.ERROR:
                        error();
                        if (msg.obj.toString().contains("网络异常")) {
                            ToastShow.showShort(mActivity, "请求差分数据异常，将直接使用GPS数据!");
                        } else {
                            ToastShow.showShort(mActivity, (String) msg.obj);
                        }

                        break;


                }
            }
        };
    }

    private void error() {
        if (currentPt != null) {
            currentPt = Gps2BaiDu.to(currentPt);//获取差分数据
            if (currMark == null) {
                addPoint();
            } else {
                currMark.setPosition(currentPt);
            }
            DGPSHandler.sendEmptyMessage(SUCCEED);
        }

    }

    /**
     * 获取差分值*
     */
    private void getDifferenceData() {
        MyApp.HTTP.GetDifferenceData(DGPSHandler, HttpStringUtil.SUCCESSED, currentPt.longitude, currentPt.latitude);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GPSCODE) {
            if (MyApp.gps_tool == null) MyApp.gps_tool = GPS_TOOL.getIntence(this);//实例化定位类

            if (MyApp.gps_tool.openGPSSettings())//检查定位GPS是否打开?
            {
                //如打开开始定位
                openDGPS();//DGPS定位
            } else {

                ChangeGPSStyle();

            }
        } else if (requestCode == 200) {
            //魔盒返回地址
            if (resultCode == RESULT_OK) {
                ToastShow.showShort(this, "蓝牙已打开,开始搜索");
                mohe.search();
            } else {
                ToastShow.showShort(this, "蓝牙没有打开");
                finish();
            }
        }


    }


    /**
     * 获取点位列表*
     */

    private void getExplorationList() {
        if (MyApp.isOnLine) {
            MyApp.HTTP.getExplorationList(pointHandler, HttpStringUtil.SUCCESSED, projectType, MyApp.currProject.getStage_id(), "");//获取踏勘点列表
        } else {
            if (pointData == null) {
                pointData = GetFileUtil.getExplorationList(projectType);
            } else {
                pointData.clear();
                pointData.addAll(GetFileUtil.getExplorationList(projectType));
            }
            pointHandler.sendEmptyMessage(3);
        }
    }


    /**
     * 点位列表信息接收器*
     */

    private void addPointHandler() {
        pointHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (pointData == null) {
                                pointData = FastJsonUtil.JsonToGetExplorationList((String) msg.obj);
                            } else {
                                pointData.clear();
                                pointData.addAll(FastJsonUtil.JsonToGetExplorationList((String) msg.obj));
                            }
                            SetFileUtil.setExplorationList((String) msg.obj, projectType);
                            pointHandler.sendEmptyMessage(3);
                        } else {
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;

                    case 1:
                        addPoint();
                        for (Exploration datum : pointData) {
                            if (datum.getExploration_person().equals(MyApp.userInfo.getUser_id())) {
                                currentPt = new LatLng(Double.valueOf(datum.getLat()), Double.valueOf(datum.getLng()));
                                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));//将位置设为中心点
                                break;
                            }
                        }
                        break;
                    case 2:
                        if (span) {
                            addSpan();
                        }
                        break;
                    case 3:
                        try {
                            List<Exploration> point = new ArrayList<>();
                            for (Exploration b : pointData) {
                                if (b.pt_type.equals(MString.DWD) && !b.getFlag().equals(MString.del)) {
                                    point.add(b);
                                }
                            }
                            pointData.clear();
                            pointData.addAll(point);
                        } catch (Exception e) {

                        }
                        pointHandler.sendEmptyMessage(1);
                        break;
                    case HttpStringUtil.ERROR:
                        MyApp.File.ReadFileToSend(pointHandler, MString.ProjectStageExplorePointList + "_" + MyApp.currProject.getStage_id() + "_" + projectType);
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;

                }
            }
        };
    }

    /**
     * 加载点位并画出线段*
     */

    List<SpanBean> points = new ArrayList<>();//点位线段集合
    Marker currMark;

    private synchronized void addPoint() {
        mBaiduMap.clear();
        points.clear();
        baidumapstyle.clearmarker_Seconds();
        if (!(pointData == null || pointData.size() == 0)) {
            try {
                Map<String, Integer> map = DataUtil.getIconData(0);
                for (Exploration exploration : pointData) {
                    try {
                        if (exploration.lat != null && exploration.lng != null && exploration.lat.length() > 0 && exploration.lng.length() > 0) {
                            LatLng point = new LatLng(Double.parseDouble(exploration.lat), Double.parseDouble(exploration.lng));
                            if (corner) {
                                baidumapstyle.addMarka(exploration, mActivity, point, parseInt(map.get(exploration.pt_id).toString()));
                            } else {
                                baidumapstyle.addMarka(exploration, point, parseInt(map.get(exploration.pt_id).toString()));
                            }

                            if (exploration.before_lat != null && exploration.before_lng != null && exploration.before_lat.length() > 0 && exploration.before_lng.length() > 0) {
                                LatLng p1 = new LatLng(Double.parseDouble(exploration.lat), Double.parseDouble(exploration.lng));
                                LatLng p2 = new LatLng(Double.parseDouble(exploration.before_lat), Double.parseDouble(exploration.before_lng));
                                points.add(new SpanBean(new LatLng((p1.latitude + p2.latitude) / 2, (p1.longitude + p2.longitude) / 2), exploration.distance));
                                List<LatLng> points = new ArrayList<LatLng>();
                                points.add(p1);
                                points.add(p2);
                                OverlayOptions ooPolyline = new PolylineOptions().width(10)
                                        .color(R.color.red).points(points);
                                mBaiduMap.addOverlay(ooPolyline);
                            }
                        }
                    } catch (Exception e) {
                    }
                }
                pointHandler.sendEmptyMessage(2);
            } catch (Exception e) {
            }
        }
        if (currentPt != null) {
            try {
                if (isGps || isBox) {
                    //加载mark
                    currMark = baidumapstyle.addMarka(currentPt);
                }
                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));//将位置设为中心点
            } catch (Exception e) {
            }
        }
        if (radioButton3.isChecked()) addPoint_Click();
    }


    //依据档距划出可选点位范围
    private synchronized void addPoint_Click() {
        mBaiduMap.removeMarkerClickListener(listener);
        mBaiduMap.setOnMarkerClickListener(listener);
    }

    private BaiduMap.OnMarkerClickListener listener = new BaiduMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            MyDialog.setPointDistance(mActivity, marker.getPosition(), mBaiduMap, pointData);
            return true;
        }
    };


    /**
     * 显示与隐藏*
     */
    public void disPlay(View v) {
        if (disPlay) {
            disPlay = false;
            //显示中需要隐藏
            headsecond_button_item.setVisibility(View.GONE);
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.fold));
        } else {
            disPlay = true;
            //隐藏中需要显示
            headsecond_button_item.setVisibility(View.VISIBLE);
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.unfold));
        }

    }

    //下一步
    public void buttonClick(View v) {
        //按钮点击后跳转界面保存数据
        if (MyApp.currProject.getProject_id().length() == 0 && MyApp.currProject.getUUID().length() == 0) {
            ToastShow.showShort(this, "请选择一个项目！");
            return;
        }
        ChangeGPSStyle();
        if (mohe != null) mohe.close();
        intentToNext();//直接跳转到下一界面

    }

    private void intentToNext() {
        try {
            if (bean.getCurrentPt().latitude < 0 || bean.getCurrentPt().longitude < 0 || bean.getCurrentPt().latitude == 4.9E-324 || bean.getCurrentPt().longitude == 4.9E-324) {
                ToastShow.showShort(this, "定位异常！");
                return;
            }
            MyApp.currExploration.setLat(bean.getCurrentPt().latitude + "");
            MyApp.currExploration.setLng(bean.getCurrentPt().longitude + "");
            MyApp.currExploration.setAlt(bean.getAltitude());
            MyApp.currExploration.setLocation_way(bean.getType());

            IntentToActivity.intent(this, BitTypeActivity.class);
        } catch (Exception e) {
            ToastShow.showShort(this, "定位异常！");
        }

    }

    private void GPS() {
        getGps = true;
        if (myListener != null) {
            myListener.setCountinue(false);
            myListener.close();
        }

        startDGPS();
    }

    /**
     * 设置地图拖拽取坐标*
     */
    public void SetOnMapStatusChangeListener() {
        BaiduMap.OnMapStatusChangeListener onMapStatusChangeListener = new BaiduMap.OnMapStatusChangeListener() {
            LatLng startLng, finishLng;

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
                startLng = mapStatus.target;
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                // 滑动搜索(手机+非GPS、外设+非魔盒)
                if (((changeRTK == R.mipmap.signal_phone) && !isGps) || (!isBox && changeRTK == R.mipmap.signal_rtk)) {
                    drag_mark.setVisibility(View.VISIBLE);
                    finishLng = mapStatus.target;
                    if (startLng == null || finishLng == null) return;
                    if (startLng.latitude != finishLng.latitude
                            || startLng.longitude != finishLng.longitude) {
                        currentPt = mBaiduMap.getMapStatus().bound.getCenter();
                        bean.setCurrentPt(currentPt);
                        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));//将位置设为中心点
                        updeteData(bean);
                    }
                }
            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }
        };
        mBaiduMap.setOnMapStatusChangeListener(onMapStatusChangeListener);

    }


    //定位回调函数
    @Override
    public void updateMapState(LatLng currentPt) {
        if (ReconnaissanceActivity.currentPt != null && currentPt != null && currentPt.longitude == ReconnaissanceActivity.currentPt.longitude && currentPt.latitude == ReconnaissanceActivity.currentPt.latitude) {
            mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));//将位置设为中心点
            return;
        }
        ReconnaissanceActivity.currentPt = new LatLng(currentPt.latitude, currentPt.longitude);
        if (myListener != null) {
            MyApp.bdLocation = myListener.getBDLocation();
            location = myListener.getBDLocation();
        } else {
            location = MyApp.bdLocation;
        }

        if (location == null) return;
        if (location.getSatelliteNumber() == -1) {
            bean.setStrengthValue(0 + "");
        } else {
            bean.setStrengthValue(location.getSatelliteNumber() + "");
        }


        if (location.getAltitude() == 4.9E-324) {
            bean.setAltitude("");
        } else {
            bean.setAltitude(location.getAltitude() + "");
        }

        bean.setAccuracy(location.getRadius() + "");
        bean.setCurrentPt(currentPt);
        mBaiduMap.clear();
        if (currMark == null) {
            addPoint();
        } else {
            currMark.setPosition(currentPt);
        }
        updeteData(bean);
    }

    //默认设置拖动定位
    @Override
    protected void onResume() {
        if (baidumapstyle != null) baidumapstyle.onResume();
        MyApp.currExploration.clear();
        MyApp.isDistance = false;//每次进入都将清空数据
        mActivity = this;
        MyApp.activity = this;
        if (isonResumeupdate) {
            getExplorationList();
            radioButton3.setChecked(true);
        } else {
            isonResumeupdate = true;
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (baidumapstyle != null) baidumapstyle.onPause();
        super.onPause();
    }

    private void closeGps() {
        isGps = false;
        getGps = false;
        if (loadutil != null) loadutil.outClear();
        if (myListener != null) {
            myListener.close();
            myListener.setCountinue(false);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        isGps = true;
    }


    boolean span = false;
    boolean corner = false;

    //转角
    public void corner(View v) {
        if (corner) {
            corner = false;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.displaycorner));
        } else {
            corner = true;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.hiddencorner));
        }
        addPoint();

    }


    //档距
    public void span(View v) {
        if (span) {
            span = false;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.displayspan));
            addPoint();
            MyLog.L(MString.SUCCESSED + " 档距span=" + span);
        } else {
            span = true;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.hiddenspan));
            addSpan();
        }
    }

    private void addSpan() {
        MyLog.L(MString.SUCCESSED + " 档距points=" + JSON.toJSONString(points));
        MyLog.L(MString.SUCCESSED + " 档距span=" + span);
        if (points.size() > 0) {
            for (SpanBean s : points) {
                if (!(s.distance == null || s.distance.length() == 0)) {
                    baidumapstyle.addMarka(mActivity, s.distance, s.point);
                }

            }
        }
    }
}
